package handlers

import (
	"art-man-sys/cache"
	"art-man-sys/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"message": "字段不可为空",
			"code":    500,
		})
		return
	}
	data := models.Article{

		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "数据库添加失败",
			"code":    500,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "add",
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := models.DB.Debug().Where("id = ?", id).Delete(&models.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var article []models.Article

	redis_list_ley := "list_article"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if result == "" {
		models.DB.Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(result), &article)
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "成功",
		"data":    article,
	})
	return
}
